#include "mealdatareader.h"
#include <QDebug>

MealDataReader::MealDataReader(QSqlQuery *q, QSqlDatabase *db, QObject *parent) :
    QObject(parent)
{
    m_query = q;
    m_db = db;
}



void MealDataReader::readFile(QString fn, bool flush)
{
    m_db->transaction();
    QFile file(fn);
    if (flush) {
        if(!m_query->exec("DELETE FROM foods")) {
            qWarning() << "Unable to truncate";
        } else {
            qWarning() << "truncated";
        }
    }
    DataReadStatus ds;
    QString addQuery;
    QFile out("out.sql");
    out.open(QFile::ReadWrite);
    QString currentLineData;
    MealData currentData;
    if (file.open(QFile::ReadOnly)) {
        char currentChar;
        while (file.getChar(&currentChar)) {
            if (currentChar == '&') {
                if (currentLineData.length() > 2) {
                    currentLineData = currentLineData.mid(2); // strip out the a_ part

                    int spacePos0 = currentLineData.indexOf('_');
                    currentData.group = currentLineData.left(spacePos0).toInt()+1;
                    currentLineData = currentLineData.mid(spacePos0 + 1);
                    spacePos0 = currentLineData.indexOf('_');

                    int groupId =  currentLineData.left(spacePos0).toInt();
                    currentLineData = currentLineData.mid(spacePos0 + 1);
                    QString key = currentLineData.left(currentLineData.indexOf('='));

                    if (key == "id") {
                        currentData.id = currentLineData.mid(3).toInt();
                        ds.id = true;
                    } else if (key == "n") {
                        currentData.name = convertName(currentLineData.mid(2)).toAscii();
                        ds.name = true;
                    } else if (key == "q") {
                        currentData.amount = convertName(currentLineData.mid(2)).toAscii();
                        ds.amount = true;
                    } else if (key == "en") {
                        currentData.energia = currentLineData.mid(3).toDouble();
                        ds.calorie = true;
                    } else if (key == "pr") {
                        currentData.feherje = currentLineData.mid(3).toDouble();
                        ds.protein = true;
                    } else if (key == "ch") {
                        currentData.szenhidrat = currentLineData.mid(3).toDouble();
                        ds.ch = true;
                    } else if (key == "fat") {
                        currentData.fat = currentLineData.mid(4).toDouble();
                        ds.fat = true;
                    }

                    if (ds.isCompete()) {
                        ds.reset();
                        collectedData.append(currentData);
                        addQuery = QString("INSERT INTO foods (foodType, foodName, foodCalorie, foodProtein, foodCh, foodFat, foodUnit)"
                                           " VALUES (%1, \"%2\", %3, %4, %5, %6, \"%7\");\n")
                                .arg(currentData.group)
                                .arg(currentData.name)
                                .arg(currentData.energia)
                                .arg(currentData.feherje)
                                .arg(currentData.szenhidrat)
                                .arg(currentData.fat)
                                .arg(currentData.amount);
                        //qWarning() << addQuery;
                        out.write(QString(addQuery+"\n").toAscii());
                        if (m_query->exec(addQuery) == false) {
                            qWarning() << m_query->lastError().databaseText() << m_query->lastError().driverText();
                        } else {
                            qWarning() << "added";
                        }
                    }
                }
                currentLineData.clear();
            } else {
                currentLineData.append(currentChar);
            }
        }
        file.close();
        out.write(addQuery.toAscii());
        out.close();
        m_db->commit();
    }
}


QString MealDataReader::convertName(QString inStr)
{
    if (inStr.contains('%')) {
        while (inStr.contains('%')) {
            int szazalekPlace = inStr.indexOf('%');
            bool ok;
            QString outChar = QString("%1").arg(QChar(inStr.mid(szazalekPlace+1, 2).toInt(&ok, 16))).toAscii();
            inStr.replace(szazalekPlace, 3, outChar);
        }
    }

    inStr.replace("+", " ");
    return inStr;
}
